<?php

session_start();

include "connect.php";

$product_id = $_POST['product_id'];
$guest_email = $_POST['customer_email'];
$today = date("Y/m/d");
	
$result = mysql_query("SELECT * FROM customer_alerts WHERE customer_email = '$guest_email' AND product_id ='$product_id'");
$num_rows = mysql_num_rows($result);

if($num_rows == 0) //if the customer email doesnt have an alert already

	{
	
		mysql_query("INSERT INTO customer_alerts 

		(
		
		product_id,
		alert_created,
		status,
		customer_email
		
		) 
	
		VALUES
	
		(
	
		'$product_id',
		'$today',
		'Active',
		'$guest_email')
	
		"); 
		
		/////////////////////////
		//Send confirmation email
		/////////////////////////
		
		// 1. Check if customers email is on the unregistered list
		// 2. If it isnt on the list then email is sent to the customer
		
		// 1		
		$query = "SELECT * FROM unregistered_emails WHERE email_address = '$guest_email'";
		$result = mysql_query($query);
		$count = mysql_num_rows($result);
		
		// 2
		if($count == 0)
		
			{
				
			$email_query = "SELECT * FROM saddles WHERE product_id = '$product_id'";
			$email_result = mysql_query($email_query);
			while($row = mysql_fetch_array($email_result))
		
				{
			
				$saddle_name = $row['product_name'];
				$saddle_row_id = $row['id'];
				$link = $row['link'];
		
				}
		
			$to      = $guest_email;
			$subject = 'Your saddle alert has been created';
			
			$message = file_get_contents('admin_files/emails/alert_confirmation.html');
			$message = $change = str_replace("{SADDLE_NAME}", $saddle_name, $message);
			$message = $change = str_replace("{SADDLE_ROW_ID}", $saddle_row_id, $message);
			$message = $change = str_replace("{CUSTOMER_EMAIL}", $guest_email, $message);
			$message = $change = str_replace("{PRODUCT_LINK}", $link, $message);
			$headers = "From: 24-7Saddles.com <Sales@24-7saddles.com>\r\n";
			$headers .= "MIME-Version: 1.0\r\n";
			$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

			mail($to, $subject, $message, $headers);
			
			header("Location: http://24-7saddles.com");
		
			}
			
			else
			
			{
			
			header("Location: http://24-7saddles.com");
			
			}
	
	};
		
/////
//End
/////

header("Location: http://24-7saddles.com");

//echo $count;

?>